<template>
  <md-popup id="popup-container" v-model="value" position="bottom" :has-mask="true" prevent-scroll @hide="cancel">
    <div id="searcher">
      <div class="city-name" @click="selectCity" v-if="!selectCityMode">
        <div>{{selectedCity.city}}</div>
        <md-icon name="city_next" style="width:18px;height:8px;margin-left:8px;"></md-icon>
      </div>
      <md-input-item
        @focus="onCitySearcherFocus"
        type="text"
        v-model="cityValue"
        class="city-input"
        ref="cityInput"
        :placeholder="'请输入城市'"
        v-if="selectCityMode"
      >
        <md-icon name="clear_icon" slot="right" v-show="cityValue!=''" @click="clearCityValue"></md-icon>
      </md-input-item>
      <md-input-item
        @focus="onPoiSearcherFocus"
        type="text"
        v-model="searchValue"
        class="searcher-input"
        ref="searcherInput"
        :placeholder="hintString"
        v-show="!selectCityMode"
      >
        <md-icon name="clear_icon" slot="right" v-show="searchValue!=''" @click="clearSearchValue"></md-icon>
      </md-input-item>
      <div class="searcher-btn" @click="cancel">取消</div>
    </div>
    <incity-poi-list
      class="box-container"
      :searchList="searchList"
      :poiList="poiList"
      :historyList="incityHistoryAddress"
      @onItemSelect="onItemSelect"
      v-if="!selectCityMode"
      :isStart="isStart"
    ></incity-poi-list>
    <incity-city-list v-if="selectCityMode" @submit="onCitySubmit" :searchValue="cityValue" @ready="onCityListReady" @gotoCurrentLocation="gotoCurrentLocation"></incity-city-list>
    <!-- <md-scroll-view
            ref="scroller"
            class="box-container"
            :auto-reflow="true"
            :scrolling-x="false"
            :bouncing="false">
            <md-field class="field-list" v-if="searchList.length>0">
                <search-item
                    type="search"
                    v-for="(item,index) in searchList"
                    :key="index"
                    :info="item"
                    @select="onItemSelect(item)"></search-item>
            </md-field>
            <md-field class="field-list" v-if="searchList.length==0">
                <search-item
                    type="search"
                    v-for="(item,index) in poiList"
                    :key="index"
                    :info="item"
                    @select="onItemSelect(item)"></search-item>
            </md-field>
    </md-scroll-view>-->
  </md-popup>
</template>

<script>
import '@/assets/svgs/city_next.svg';
import '@/assets/svgs/taxi_add_kst.svg';
import '@/assets/svgs/clear_icon.svg';
import SearchItem from './SearchItem';
import PositionList from './PositionList';
import CityList from './CityList';
import { Field, ScrollView, Popup, Icon, InputItem } from 'mand-mobile';
import { mapGetters } from 'vuex';
export default {
  name: 'search-box',
  components: {
    [SearchItem.name]: SearchItem,
    [PositionList.name]: PositionList,
    [CityList.name]: CityList,
    [Field.name]: Field,
    [ScrollView.name]: ScrollView,
    [Popup.name]: Popup,
    [Icon.name]: Icon,
    [InputItem.name]: InputItem
  },
  data() {
    return {
      searchValue: '',
      autoComplete: null,
      selectCityMode: false,
      cityValue: '',
      searchList: [],
      poiList: [],
      selectedCity: {}
    };
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    isStart: {
      type: Boolean,
      default: true
    },
    type: {
      // 1:拼车、2:包车
      type: String,
      default: '1'
    },
    appendTo: {
      default: () => document.body
    },
    searchs: {
      type: Array,
      default: () => {
        return [];
      }
    },
    startOk: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    searchValue: 'onValueChange'
  },
  methods: {
    onValueChange(value) {
      if (!this.autoComplete) {
        return;
      }
      this.autoComplete.search(value, (status, result) => {
        if (typeof result !== 'string') {
          if (result.tips && result.tips.length > 0) {
            let arr = [];
            result.tips.forEach((item, index) => {
              if (!item.location) {
                return;
              }
              let obj = {
                stationName: item.name,
                position: item.district + item.address,
                coordinate: [item.location.lng, item.location.lat].join(','),
                adcode: item.adcode
              };
              arr.push(obj);
            });
            this.searchList = arr;
          }
        }
      });
    },
    clearCityValue() {
      this.cityValue = '';
    },
    clearSearchValue() {
      this.searchValue = '';
    },
    onItemSelect(item) {
      this.$emit('submit', item);
    },
    onCitySearcherFocus() {
      console.log('focus');
    },
    onCityListReady() {
      if (this.$refs.cityInput) {
        this.$refs.cityInput.focus();
      }
    },
    onPoiSearcherFocus() {
      this.selectCityMode = false;
    },
    selectCity() {
      if (this.isStart) {
        this.selectCityMode = true;
        if (this.$refs.cityInput) {
          this.$refs.cityInput.focus();
        }
      }
    },
    cancel() {
      if (this.selectCityMode) {
        this.selectCityMode = false;
      } else {
        this.value = false;
        this.$emit('cancel');
      }
    },
    gotoCurrentLocation() {
      console.log(this.getCurrentLocation);
      this.changeAutoCompleteOption(this.getCurrentLocation.provinceCode);
      this.selectCityMode = false;
      this.getPoiListByCoords(this.getCurrentLocation.coordinate, this.getCurrentLocation.provinceCode);
      this.selectedCity.city = this.getCurrentLocation.provinceName;
    },
    changeAutoCompleteOption(cityCode) {
      if (this.autoComplete) {
        this.autoComplete.setCity(cityCode);
        this.autoComplete.setCityLimit(true);
      }
    },
    onCitySubmit(city) {
      this.poiList = [];
      this.searchList = [];
      this.selectedCity = city;
      this.changeAutoCompleteOption(city.adCode);
      this.selectCityMode = false;
      this.$store.dispatch('getIncityCityInfoById', city.cityId).then(cityInfo => {
        let coords = cityInfo.snEfncePort.split(',');
        let adcode = city.adcode;
        this.getPoiListByCoords(coords, adcode);
      });
    },
    getPoiListByCoords(coords, adcode) {
      AMap.plugin('AMap.PlaceSearch', () => {
        let searcher = new AMap.PlaceSearch({
          city: adcode,
          pageSize: 15,
          pageIndex: 1
        });
        searcher.searchNearBy('', coords, 1000, (status, result) => {
          this.$refs.searcherInput.focus();
          if (status === 'complete' && result.info === 'OK') {
            this.poiList = [];
            result.poiList.pois.forEach((item, index) => {
              if (item.address !== '') {
                let obj = {
                  stationName: item.name,
                  position: item.address,
                  coordinate: [item.location.lng, item.location.lat].join(','),
                  adcode: this.incityStartPosition.adcode
                };
                if (index === 0 || index === 1 || index === 2) {
                  obj.tuijian = true;
                }
                this.poiList.push(obj);
              }
            });
          }
        });
      });
    }
  },
  created() {
    if (this.incityInfo) {
      this.selectedCity.city = this.incityInfo.cityName;
      console.log(this.incityInfo.cityName);
      var provinceCode = this.incityInfo.country.split('_')[2];
      console.log(provinceCode);
      AMap.plugin('AMap.Autocomplete', () => {
        let autoOptions = {
          city: this.isStart ? provinceCode : '',
          citylimit: this.isStart
        };
        // let autoOptions = {
        //     city: this.isStart ? this.getCurrentLocation.provinceCode : '',
        //     citylimit: this.isStart
        // };
        this.autoComplete = new AMap.Autocomplete(autoOptions);
      });
      if (this.isStart && this.startOk) {
        if (this.incityStartPosition && this.incityStartPosition.coordinate !== '') {
          this.getPoiListByCoords(this.incityStartPosition.coordinate, this.incityStartPosition.adcode);
        }
      }
    } else {
      this.selectedCity.city = '北京市';
      AMap.plugin('AMap.Autocomplete', () => {
        this.autoComplete = new AMap.Autocomplete();
      });
    }
  },
  mounted() {
    if (this.appendTo) {
      this.appendTo.appendChild(this.$el);
    }
  },
  beforeDestroy() {
    if (this.appendTo) {
      this.appendTo.removeChild(this.$el);
    }
  },
  computed: {
    hintString() {
      return this.isStart ? '您从哪儿上车' : '您要去哪儿';
    },
    hasList() {
      if (this.searchs.length > 0 || this.poiList.length > 0) {
        return true;
      } else {
        return false;
      }
    },
    ...mapGetters(['getCurrentLocation', 'incityStartPosition', 'incityHistoryAddress', 'incityInfo'])
  }
};
</script>

<style lang="stylus" scoped>
#popup-container {
  height: 100vh;
  width: 100vw;
  background-color: transparent;
  position: absolute;

  .field-list {
    margin-top: 20px;
  }

  #searcher {
    background-color: #F8F8F8;
    font-size: 28px;
    height: 100px;
    padding-left: 30px;
    padding-right: 30px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    .city-name {
      min-width: 3em;
      max-width: 8em;
      color: #666;
      padding-right: 20px;
      border-right: 1px solid #E0E0E0;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
    }

    .city-input {
      border: 0px;
      outline: none;
      background-color: transparent;
      width: 5em;
      font-size: 28px;
    }

    .searcher-input {
      padding-left: 20px;
      border: 0px;
      outline: none;
      background-color: transparent;
      flex: 1;
      font-size: 26px;
      height: 88px;
    }

    .searcher-btn {
      color: #888888;
      padding-left: 20px;
      font-size: 26px;
    }
  }

  .box-container {
    height: calc(100vh - 100px);
  }

  .no-result {
    height: calc(100vh - 100px);
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;

    .innter {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-bottom: 300px;

      .text {
        font-size: 28px;
        color: rgba(102, 102, 102, 1);
      }
    }
  }
}
</style>
